package com.wuwei.tms.workbench.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.tms.pojo.Borrow;
import com.wuwei.tms.pojo.History;
import com.wuwei.tms.pojo.User;
import com.wuwei.tms.setting.mapper.UserMapper;
import com.wuwei.tms.utils.result.Result;
import com.wuwei.tms.vo.HistoryExcel;
import com.wuwei.tms.vo.HistoryPrint;
import com.wuwei.tms.workbench.mapper.BorrowMapper;
import com.wuwei.tms.workbench.mapper.HistoryMapper;
import com.wuwei.tms.workbench.service.HistoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuwei
 * @since 2024-01-03
 */
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private HistoryMapper historyMapper;

    @Resource
    private BorrowMapper borrowMapper;

    /**
     * 用户打印时显示所有数据的方法
     * @param borrowDate1 借用日期之前的日期
     * @param borrowDate2 借用日期之后的日期
     * @param returnDate1 归还日期之前的日期
     * @param returnDate2 归还日期之后的日期
     * @param borrowById
     * @param barcode
     * @return
     */
    @Override
    public List<HistoryPrint> listAll(LocalDateTime borrowDate1,LocalDateTime borrowDate2,
                                      LocalDateTime returnDate1,LocalDateTime returnDate2,
                                      long borrowById, long barcode,String airplaneId) {
        List<HistoryPrint> histories = new ArrayList<>();
        //如果查询条件为0，则返回空对象
        if (borrowById==-1&&barcode==-1&&borrowDate1==null&&borrowDate2==null
                &&returnDate1==null&&returnDate2==null&&"_".equals(airplaneId)) {
            return histories;
        }
        histories = historyMapper.myListForPrint(borrowDate1,borrowDate2, returnDate1,returnDate2, borrowById, barcode, airplaneId);

        findUserNameForPrint(histories);

        return histories;
    }




    /**
     * 由于查询出来的数据只有empno，没有user的姓名，为了方便显示，这里还要显示姓名，因此需要根据empno去t_user表查询姓名
     * @param histories
     */
    private void findUserNameForPrint(List<HistoryPrint> histories) {
        /**
         * 如果数据量大，这样循环查询数据库会浪费很多时间，现在使用下面的方法来做
         */
//        histories.forEach(h->{
//            LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
//            Long borrowById1 = h.getBorrowById();
//            wrapper1.eq(User::getEmpno, borrowById1);
//
//            User user1 = userMapper.selectOne(wrapper1);
//            if (user1!=null) {
//                String borrowByName = user1.getName();
//                h.setBorrowByName(borrowByName);
//            }
//            LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
//            Long returnById = h.getReturnById();
//            wrapper2.eq(User::getEmpno, returnById);
//            User user2 = userMapper.selectOne(wrapper2);
//            if (user2!=null) {
//                String returnByName = user2.getName();
//                h.setReturnByName(returnByName);
//            }
//        });
//        return histories;

        if (histories.size()==0) {
            return;
        }
        List<Long> returnIds = new ArrayList<>();
        List<Long> borrowIds = new ArrayList<>();
        histories.forEach(h->{
            returnIds.add(h.getReturnById());
            borrowIds.add(h.getBorrowById());
        });
        List<User> returnUsers = new ArrayList<>();
        List<User> borrowUsers = new ArrayList<>();
        if (returnIds.size()>0) {
            returnUsers = userMapper.selectBatchEmpnos(returnIds);
        }
        if (borrowIds.size()>0) {
            borrowUsers = userMapper.selectBatchEmpnos(borrowIds);
        }

        List<User> finalBorrowUsers = borrowUsers;
        List<User> finalReturnUsers = returnUsers;
        histories.forEach(h->{
            Long borrowById = h.getBorrowById();
            Optional<User> borrowUser  = finalBorrowUsers.stream().filter(u -> u.getEmpno().equals(borrowById)).findFirst();
            borrowUser.ifPresent(user -> h.setBorrowByName(user.getName()));

            Long returnById = h.getReturnById();
            Optional<User> returnUser = finalReturnUsers.stream().filter(u -> u.getEmpno().equals(returnById)).findFirst();
            returnUser.ifPresent(user -> h.setReturnByName(user.getName()));
        });
    }

    /**
     * 先从t_history表查询。t_history表查询无数据再从t_borrow表查询
     * @param borrowDate1 借用日期之前的日期
     * @param borrowDate2 借用日期之后的日期
     * @param returnDate1 归还日期之前的日期
     * @param returnDate2 归还日期之后的日期
     * @param borrowById
     * @param barcode
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public List<HistoryExcel> getList(LocalDateTime borrowDate1,LocalDateTime borrowDate2,
                                      LocalDateTime returnDate1,LocalDateTime returnDate2,
                                      long borrowById, long barcode,String airplaneId,
                                      int currentPage, int pageSize) {
        List<HistoryExcel> histories = new ArrayList<>();
        //如果查询条件为0，则返回空对象
        if (borrowById==-1&&barcode==-1&&borrowDate1==null&&borrowDate2==null
                &&returnDate1==null&&returnDate2==null&&"_".equals(airplaneId)){
            return histories;
        }
        int offset = (currentPage-1)*pageSize;
        histories = historyMapper.myListAndPage(borrowDate1,borrowDate2, returnDate1,returnDate2, borrowById, barcode,airplaneId, offset, pageSize);

        findUserNameForExcel(histories);

        return histories;
    }

    @Override
    public long total(LocalDateTime borrowDate1,LocalDateTime borrowDate2,
                      LocalDateTime returnDate1,LocalDateTime returnDate2,
                      long borrowById, long barcode,String airplaneId) {

        LambdaQueryWrapper<History> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Borrow> queryWrapper1 = new LambdaQueryWrapper<>();
        //如果查询条件为0，则返回空对象
        if (borrowById==-1&&barcode==-1&&borrowDate1==null&&borrowDate2==null
                &&returnDate1==null&&returnDate2==null&&"_".equals(airplaneId)) {
            return 0L;
        }

        //这里需要查询history和borrow两张表
        queryWrapper1.eq(Borrow::getReturnFlag,1);

        queryWrapper.eq(borrowById!=-1,History::getBorrowById,borrowById);
        queryWrapper1.eq(borrowById!=-1,Borrow::getBorrowById,borrowById);

        //查询工具编号的借用记录
        queryWrapper.eq(barcode!=-1,History::getBarcode,barcode);
        queryWrapper1.eq(barcode!=-1,Borrow::getBarcode,barcode);

        //根据飞机编号查询
        queryWrapper.eq(!"".equals(airplaneId),History::getAirplaneId,airplaneId);
        queryWrapper1.eq(!"".equals(airplaneId),Borrow::getAirplaneId,airplaneId);

        //根据借用时间和归还时间查询
        queryWrapper.ge(borrowDate1!=null,History::getBorrowTime,borrowDate1)
                .le(borrowDate2!=null,History::getBorrowTime,borrowDate2)
                .ge(returnDate1!=null,History::getReturnTime,returnDate1)
                .le(returnDate2!=null,History::getReturnTime,returnDate2);

        queryWrapper1.ge(borrowDate1!=null,Borrow::getBorrowTime,borrowDate1)
                .le(borrowDate2!=null,Borrow::getBorrowTime,borrowDate2)
                .ge(returnDate1!=null,Borrow::getReturnTime,returnDate1)
                .le(returnDate2!=null,Borrow::getReturnTime,returnDate2);

        Long count1 = historyMapper.selectCount(queryWrapper);
        Long count2 = borrowMapper.selectCount(queryWrapper1);
        return count1+count2;
    }

    @Override
    public List<HistoryExcel> download(LocalDateTime borrowDate1,LocalDateTime borrowDate2,
                                       LocalDateTime returnDate1,LocalDateTime returnDate2,
                                       long borrowById, long barcode,String airplaneId) {

        List<HistoryExcel> list = new ArrayList<>();

        //如果查询条件为0，则返回空对象
        if (borrowById==-1&&barcode==-1&&borrowDate1==null&&borrowDate2==null
                &&returnDate1==null&&returnDate2==null&&"_".equals(airplaneId)) {
            return list;
        }
        List<HistoryExcel> histories = historyMapper.myListAndPageNotPage(borrowDate1,borrowDate2, returnDate1,returnDate2, borrowById, barcode, airplaneId);

        findUserNameForExcel(histories);

        return histories;
    }

    /**
     * 由于查询出来的数据只有empno，没有user的姓名，为了方便显示，这里还要显示姓名，因此需要根据empno去t_user表查询姓名
     * @param histories
     */
    private void findUserNameForExcel(List<HistoryExcel> histories) {

        if (histories.size()==0) {
            return;
        }
        List<Long> returnIds = new ArrayList<>();
        List<Long> borrowIds = new ArrayList<>();
        histories.forEach(h->{
            returnIds.add(h.getReturnById());
            borrowIds.add(h.getBorrowById());
        });
        List<User> returnUsers = new ArrayList<>();
        List<User> borrowUsers = new ArrayList<>();
        if (returnIds.size()>0) {
            returnUsers = userMapper.selectBatchEmpnos(returnIds);
        }
        if (borrowIds.size()>0) {
            borrowUsers = userMapper.selectBatchEmpnos(borrowIds);
        }

        List<User> finalBorrowUsers = borrowUsers;
        List<User> finalReturnUsers = returnUsers;
        histories.forEach(h->{
            Long borrowById = h.getBorrowById();
            Optional<User> borrowUser  = finalBorrowUsers.stream().filter(u -> u.getEmpno().equals(borrowById)).findFirst();
            borrowUser.ifPresent(user -> h.setBorrowByName(user.getName()));

            Long returnById = h.getReturnById();
            Optional<User> returnUser = finalReturnUsers.stream().filter(u -> u.getEmpno().equals(returnById)).findFirst();
            returnUser.ifPresent(user -> h.setReturnByName(user.getName()));
        });
    }


}
